<template>
    <div>
        <el-form :model="form" label-width="40px">
            <el-form-item label="名称" prop="sensorName">
                <el-input v-model="form.sensorName" disabled/>
            </el-form-item>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="站号" prop="siteNumber">
                        <el-input v-model="form.siteNumber" disabled/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="位置" prop="position">
                        <el-input v-model="form.position" disabled/>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="数值" prop="sensorValue">
                        <el-input v-model="form.sensorValue" readonly/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="单位" prop="typeUnit">
                        <el-input v-model="form.typeUnit" readonly/>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="状态">
                <span v-if="form.status==='1'">正常</span>
                <span v-else>异常</span>
            </el-form-item>

            <el-form-item label="操作">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="success" size="small" :loading="loading" @click="readSensor">{{ btnText }}
                        </el-button>
                    </el-col>
                </el-row>
            </el-form-item>

        </el-form>

    </div>
</template>

<script>

import { sendMessage } from '@/api/netty/nettyMessage'
import { getSensor } from '@/api/equipment/sensor'

export default {
    name: 'index',
    props: {
        sensor: {
            type: Object
        }
    },
    data() {
        return {
            messageObj: {
                operationType: '0',
                instruction: '1'
            },
            webClientId: this.genUUID(10, 16),
            timer: null,
            loadingTime: 20,
            // loading: null,
            loading: false,
            btnText: '读取',
            form: {}
        }
    },
    created() {
        this.form = this.sensor
    },
    destroyed() {
        if (this.ws !== undefined) {
            this.ws.close()
        }
    },
    methods: {

        readSensor() {

            this.loading = true

            this.btnText = this.loadingTime + 's'

            // 等待时长
            let time = this.loadingTime - 1
            this.timer = setInterval(() => {
                if (time === 0) {
                    this.reset()
                    this.$message.info('超时')
                } else {
                    this.btnText = time + 's'
                    --time
                }
            }, 1000)

            this.messageObj.gatewayNumber = this.form.gatewayNumber
            this.messageObj.sensorId = this.form.sensorId
            this.messageObj.webClientId = this.webClientId

            this.send2Web()
        },
        reset() {
            clearInterval(this.timer)
            // this.loading.close()
            this.loading = false
            this.btnText = '读取'
        },
        send2Web() {
            sendMessage(this.messageObj).then(response => {

                // this.form.sensorStatus = response.sensorStatus
                // this.form.sensorNewValue = response.value
                // // 赋值后无法实时更新
                // this.$forceUpdate()
                // this.$message.success('成功')

                if (response.code === 200) {
                    // 成功后建立websocket
                    let obj = {
                        'webClientId': this.webClientId,
                        'type': 'login'
                    }
                    this.sendMessage(obj)
                }

            }, error => {
                this.reset()
            })
        },
        // websocket 发送消息给服务器
        sendMessage(obj) {
            // this.$websocket.sendMsg(JSON.stringify(obj))
            // this.$websocket.sendMsg(obj)

            if (this.ws !== undefined && this.ws.readyState === 1) {
                console.log('已存在')
                // this.$websocket.sendMsg(obj)
            } else {
                this.localSocket(obj)
            }
        },
        localSocket(obj) {
            let that = this
            if ('WebSocket' in window) {
                console.log('您的浏览器支持 WebSocket')
                // console.log('that.ws', that.ws)
                if (that.ws !== undefined && that.ws.readyState === 1) {
                    console.log('存在连接')
                    return
                }

                that.ws = new WebSocket(that.$websocket.url)
                that.$websocket.setWs(that.ws)
                that.ws.onopen = function() {
                    console.log('开始连接')
                    // that.sendMessage(obj)
                    that.$websocket.sendMsg(obj)
                }
                // websocket 接收服务器消息
                that.ws.onmessage = function(result) {
                    console.log('收到websocket回复', result)
                    // console.log('回复data', result.data)
                    that.processData(result.data)
                }
                that.ws.onclose = function() {
                    // 防链接超时，（websocket在一定时间内没有数据交互，就会断开），关闭后重启
                    console.log('连接已关闭')
                    that.ws.close()
                    // setTimeout(() => {
                    //     that.localSocket()
                    // }, 2000)
                }
            } else {
                // 浏览器不支持 WebSocket
                console.log('您的浏览器不支持 WebSocket!')
            }
        },
        processData(json) {
            console.log('json', json)

            let data = {}
            try {
                data = JSON.parse(json)
            } catch (e) {
            }
            // console.log('data', data)
            let webClientId = data['webClientId']
            if (webClientId === undefined) {
                return
            }
            console.log('回复的webClientId', webClientId)

            this.reset()

            if (webClientId === this.webClientId) {
                this.$message.success('成功')
                // 重新查询
                this.querySensor()
            }
        },
        querySensor() {
            getSensor(this.form.sensorId).then(response => {
                console.log('重新获取结果', response.data)
                this.form.sensorValue = response.data.sensorValue
                this.form.status = response.data.status
            })
        }
    }
}
</script>

<style scoped>

</style>
